//
//  MovieOrMusicViewController.m
//  开心一刻
//
//  Created by lanou on 16/4/6.
//  Copyright © 2016年 刘洋. All rights reserved.
//

#import "MovieOrMusicViewController.h"
#import "Requestmanager.h"
#import "HZWModel.h"
#import "HZWTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "PlayViewController.h"
#import "AppDelegate.h"
@interface SDWebImageManager (cache)

-(BOOL)memoryCachedImageExistsForURL:(NSURL *)url;

@end

@implementation SDWebImageManager(cache)

-(BOOL)memoryCachedImageExistsForURL:(NSURL *)url
{
    NSString * key = [self cacheKeyForURL:url];
    return ([self.imageCache imageFromMemoryCacheForKey:key] != nil) ? YES : NO;
}
@end

@interface MovieOrMusicViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView * tableview;
@property(nonatomic,strong)NSMutableArray * modelArray;
@property(nonatomic,strong)UIView * oneView;
@property(nonatomic,strong)UIView * myView;
@property(nonatomic,strong)UIImageView * myImage;
@property(nonatomic,assign)CGFloat x;
@property(nonatomic,assign)CGFloat y;
@property(nonatomic,strong)UIImageView * backImage;
@property(nonatomic,strong)UILabel * titleLabel;
@property(nonatomic,strong)UIView * lineView;
@property(nonatomic,strong)UILabel * styleLabel;
@property(nonatomic,strong)UILabel * textLabel;
@property(nonatomic,strong)UIButton* playButton;
@property(nonatomic,strong)NSString* string;
@property(nonatomic,strong)UILabel * lable;

@end

@implementation MovieOrMusicViewController
-(void)request
{
    [Requestmanager requestWithUrl:@"http://baobab.wandoujia.com/api/v2/feed?_s=45d63a4701e425ae4f8041f6068cf8f1&date=1460510134054&f=iphone&net=wifi&num=7&u=70084a3a38fadebe8ed044b6fe9289513665f6ff&v=1.12.1&vc=403" requesType:requestTypeGET parDic:nil finish:^(NSData *data) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       // NSLog(@"%@",dic);
        self.modelArray =[HZWModel requestModel:dic];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableview reloadData];
        });
           } error:^(NSError *error) {
        NSLog(@"请求失败");
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self request];
   
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KedWidth, KedHeight) style:UITableViewStyleGrouped];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    [self.view addSubview:_tableview];
    [self.tableview registerClass:[HZWTableViewCell class] forCellReuseIdentifier:@"cell"];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    NSLog(@"%ld",[_modelArray[0]count]);
    return [_modelArray[0]count];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [self.modelArray[1][section]  count];
}

//添加 每个cell 出现的3D动画
-(void)tableView:(UITableView *)tableView willDisplayCell:(HZWTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HZWModel * model = self.modelArray[1][indexPath.section][indexPath.row];
    
    if (model.detail != nil) {
        if (![[SDWebImageManager sharedManager] memoryCachedImageExistsForURL:[NSURL URLWithString:model.detail]])
        {
            
            CATransform3D rotation;//3D旋转
            
            rotation = CATransform3DMakeTranslation(0 ,50 ,20);
            //        rotation = CATransform3DMakeRotation( M_PI_4 , 0.0, 0.7, 0.4);
            //逆时针旋转
            
            rotation = CATransform3DScale(rotation, 0.5, .5, 1);
            
            rotation.m34 = 1.0/ -600;
            
            cell.layer.shadowColor = [[UIColor blackColor]CGColor];
            cell.layer.shadowOffset = CGSizeMake(10, 10);
            cell.alpha = 0;
            
            cell.layer.transform = rotation;
            
            [UIView beginAnimations:@"rotation" context:NULL];
            //旋转时间
            [UIView setAnimationDuration:1];
            cell.layer.transform = CATransform3DIdentity;
            cell.alpha = 1;
            cell.layer.shadowOffset = CGSizeMake(0, 0);
            [UIView commitAnimations];
            
        }

    }
    else{
        if (![[SDWebImageManager sharedManager] memoryCachedImageExistsForURL:[NSURL URLWithString:model.image]])
        {
            
            CATransform3D rotation;//3D旋转
            
            rotation = CATransform3DMakeTranslation(0 ,50 ,20);
            //        rotation = CATransform3DMakeRotation( M_PI_4 , 0.0, 0.7, 0.4);
            //逆时针旋转
            
            rotation = CATransform3DScale(rotation, 0.5, .5, 1);
            
            rotation.m34 = 1.0/ -600;
            
            cell.layer.shadowColor = [[UIColor blackColor]CGColor];
            cell.layer.shadowOffset = CGSizeMake(10, 10);
            cell.alpha = 0;
            
            cell.layer.transform = rotation;
            
            [UIView beginAnimations:@"rotation" context:NULL];
            //旋转时间
            [UIView setAnimationDuration:0.6];
            cell.layer.transform = CATransform3DIdentity;
            cell.alpha = 1;
            cell.layer.shadowOffset = CGSizeMake(0, 0);
            [UIView commitAnimations];
            
        }

    }
  }
// 返回cell的事件
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HZWTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
   
    HZWModel * model = _modelArray[1][indexPath.section][indexPath.row];
    self.string = model.playUrl;
    cell.titleLabel.text= model.title;
    
    cell.styleLabel.text = [NSString stringWithFormat:@"#%@ / %02ld:%02ld",model.category,model.duration/60,model.duration%60];
    
    
    if (model.detail ==nil && model.image !=nil )
    {
        [cell.myImage sd_setImageWithURL:[NSURL URLWithString:model.image] completed:nil];
        cell.styleLabel.text = nil;
    }
    else{
        [cell.myImage sd_setImageWithURL:[NSURL URLWithString:model.detail] completed:nil];
    }
    
UITapGestureRecognizer * tap =[[UITapGestureRecognizer alloc]initWithTarget:self  action:@selector(tappp:)];
    cell.myview.tag = 150+indexPath.row;
    [cell.myview addGestureRecognizer:tap];
    cell.myImage.tag = indexPath.section+200;
    cell.myImage.userInteractionEnabled = YES;
    return  cell;
}


// 触发事件的方法
-(void)tappp:(UITapGestureRecognizer *)tap
{
    
    // cell 上的模板 添加了手势 通过手势找到模板
    UIView  *view = tap.view;
    NSInteger indexr = view.tag -150;
    UIView * view1 = view.superview;
    NSInteger indexs = view1.tag -200;
    HZWModel * model = _modelArray[1][indexs][indexr];
   // 通过模板找到cell
    HZWTableViewCell * cell = (HZWTableViewCell *)view.superview.superview.superview;
    _x = cell.frame.origin.x;
    _y = cell.frame.origin.y;
    self.tableview.userInteractionEnabled = NO;
    
    // 创建一个view  并且view的fram 是动态的是根据 cell的fram改变的
    self.oneView= [[UIView alloc]initWithFrame:CGRectMake(_x, _y - self.tableview.contentOffset.y, KedWidth, KedHeight/854*480)];
    self.oneView.alpha = 0;
    //self.oneView.backgroundColor =[UIColor whiteColor];
    
    // 创建清扫手势
    UISwipeGestureRecognizer * swip = [[UISwipeGestureRecognizer alloc]initWithTarget:self  action:@selector(swipAction:)];
    // 创建清扫方向
    [swip  setDirection:UISwipeGestureRecognizerDirectionUp];
    // 将手势添加到 创建好的view上
    [self.oneView addGestureRecognizer:swip];
    
    // 创建imageview 用于放cell的image
    self.myImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KedWidth, KedWidth/854*480)];
    // 创建背景图片
    self.backImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KedWidth, 0)];
    
    [self.backImage sd_setImageWithURL:[NSURL URLWithString:model.blurred] completed:nil];
    [self.oneView addSubview:_backImage];
    
    // 添加label
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 250, 30)];
    self.titleLabel.text = model.title;
    [self.titleLabel setTextColor:[UIColor whiteColor]];
    self.titleLabel.font =[UIFont fontWithName:@"Helvetica-Bold" size:15];
    [self.backImage addSubview:_titleLabel];
    
    // 添加线条
    self.lineView =[[UIView alloc]initWithFrame:CGRectMake(15, 40, 200, 1)];
    self.lineView.backgroundColor =[UIColor whiteColor];
    [self.backImage  addSubview:_lineView];
    // 添加类型
    self.styleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 46, 150, 20)];
    self.styleLabel.font =[UIFont systemFontOfSize:13];
    self.styleLabel.textColor =[UIColor whiteColor];
    self.styleLabel.text  = cell.styleLabel.text;
    [self.backImage addSubview:_styleLabel];
    
    // 添加内容
    self.textLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 46+20+5,KedWidth -30,(KedHeight -KedHeight/1.7)-46-20-5-55)];
    self.textLabel.text =  model.descriptionx;
    self.textLabel.backgroundColor  = [UIColor whiteColor];
    _textLabel.backgroundColor = [UIColor clearColor];
    _textLabel.numberOfLines = 0;
    _textLabel.textColor =[UIColor whiteColor];
    _textLabel.font =[UIFont systemFontOfSize:13];
    [self.backImage addSubview:_textLabel];
   // 添加播放按钮
    self.playButton =[UIButton buttonWithType:UIButtonTypeCustom];
    self.playButton .frame = CGRectMake((KedWidth-60)/2,( KedHeight -KedHeight/1.7+64+60)/2, 60, 60);
    [self.playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    self.playButton .layer.masksToBounds = YES;
    self.playButton.layer.cornerRadius = 30;
    [self.playButton addTarget:self action:@selector(playButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.myImage addSubview:_playButton];
    
    self.myImage.userInteractionEnabled = YES;
    self.myImage.image = cell.myImage.image;
    [self.oneView addSubview:_myImage];
    [self.view addSubview:_oneView];
    [UIView animateWithDuration:1 animations:^{
        self.oneView.alpha = 1;
        self.myImage.alpha = 1;
        self.oneView.frame = CGRectMake(0, 0, KedWidth, KedHeight);
        self.myImage.frame = CGRectMake(0, 0, KedWidth, KedHeight/1.7);
        self.backImage .frame = CGRectMake(0, KedHeight/1.7, KedWidth, KedHeight -KedHeight/1.7);
        }];
    
    _lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 64, KedWidth, 30)];
    _lable.text = @"向上滑动可以返回上一届面";
    _lable.textAlignment = NSTextAlignmentCenter;
    [self.oneView addSubview:_lable];
    _lable.backgroundColor = [UIColor purpleColor];
    NSTimer * one = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(aaa:) userInfo:nil repeats:NO];
    
    
    
   }
- (void)aaa:(NSTimer *)one
{
    _lable.hidden = YES;
}

// 点击播放事件
-(void)playButton:(UIButton *)button
{
    PlayViewController * pl =[[PlayViewController alloc]init];
    pl.string = self.string;
    AppDelegate * app = [UIApplication sharedApplication].delegate;
    app.isOk = YES;
    [self presentViewController:pl animated:NO completion:nil];
    
}
// 清扫手势
-(void)swipAction:(UITapGestureRecognizer *)tap
{
    self.playButton.hidden = YES;

    [UIView animateWithDuration:0.35 animations:^{
        NSLog(@"%lf",_y );
        self.oneView.frame = CGRectMake(_x, _y - self.tableview.contentOffset.y, KedWidth, KedWidth/854*480);
        self.myImage.frame = CGRectMake(0, 0, KedWidth, KedWidth/854*480);
        self.backImage.frame = CGRectMake(0, 0, KedWidth, 0);
    } completion:^(BOOL finished) {
        [self.oneView removeFromSuperview];
        self.oneView.alpha = 0;
        self.tableview.userInteractionEnabled = YES;
            }];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HZWModel * model=_modelArray[0][section];
    UIView * view  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KedWidth, 60)];
    view.backgroundColor = [UIColor whiteColor];
   // CGRect framerect = CGRectMake(0, 0, 100, 40)
    if (model.image !=nil)
    {
        UIImageView * viewx = [[UIImageView alloc]initWithFrame:CGRectMake(50, 10, KedWidth - 100, 40)];
        [viewx sd_setImageWithURL:[NSURL URLWithString:model.image]];
        [view addSubview:viewx];
    }
    else{
    UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(100, 20, KedWidth - 200, 20)];
    lable.text = model.text;
        lable.textAlignment = NSTextAlignmentCenter  ;
        [view addSubview:lable];
    }
    return view;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return KedWidth/854*480;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
